//
//  FileUtil.m
//  Weike
//
//  Created by leirz on 14-7-24.
//  Copyright (c) 2014年 winupon. All rights reserved.
//

#import "FileUtil.h"
#import "AppUtils.h"

@implementation FileUtil

+ (NSString *)getRootDir
{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
//    return @"/Users/apple/Desktop/document";//
    
//  应用名称.app/Framework 目录
//  NSString *framePath = [[NSBundle mainBundle] privateFrameworksPath];
//  framePath =  [framePath substringToIndex:framePath.length-11];
//  NSLog(@"%@---%zi",framePath,[FileUtil isFileDir:framePath]);
//  return framePath;
}

+ (NSString *)getFullPath:(NSString *)path
{
    if ([path hasPrefix:@"http"] || [path hasPrefix:@"/var"]) {
        return path;
    }
    return [NSString stringWithFormat:@"%@%@", [self getRootDir], path];
}

+ (NSString *)getRelativeDir:(NSString *)userId cacheType:(NSString *)cacheType
{
    return [NSString stringWithFormat:@"/%@/%@", userId, cacheType];
}

+ (NSString *)toRelativePath:(NSString *)path
{
    NSString *rootDir = [self getRootDir];
    return [path stringByReplacingOccurrencesOfString:rootDir withString:@""];
}

+ (NSString *)getUpdateDir:(NSString *)userId cacheType:(NSString *)uploadType
{
    uploadType = @"fileDownload";
    NSString *uploadDir = [NSString stringWithFormat:@"%@/%@/%@", [FileUtil getRootDir], uploadType,userId];
    [FileUtil mkdirs:uploadDir];
//    return [FileUtil getRootDir];//uploadDir;
    return uploadDir;
}


+ (NSString *)getCacheDir:(NSString *)userId cacheType:(NSString *)cacheType
{
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    cacheDir = [NSString stringWithFormat:@"%@/%@/%@", cacheDir, userId, cacheType];
    [FileUtil mkdirs:cacheDir];
    return cacheDir;
}

+ (NSString *)getResourcesDir
{
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    cacheDir = [NSString stringWithFormat:@"%@/%@", cacheDir, @"resources"];
    [FileUtil mkdirs:cacheDir];
    return cacheDir;
}

+ (NSString *)getRandomString
{
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""].lowercaseString;
}

+ (NSString *)getRandomFileName:(NSString *)extension
{
    return [NSString stringWithFormat:@"%@%@", [FileUtil getRandomString], extension];
}

+ (NSString *)getRandomPath:(NSString *)userId cacheType:(NSString *)cacheType extension:(NSString *)extension
{
    NSString *cacheDir = [FileUtil getCacheDir:userId cacheType:cacheType];
    NSString *fileName = [FileUtil getRandomFileName:extension];
    return [NSString stringWithFormat:@"%@/%@", cacheDir, fileName];
}

+ (void)mkdirs:(NSString *)dir
{
    if (![FileUtil exists:dir]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

+ (void)mkdirsAtPath:(NSString *)path
{
    NSRange range = [path rangeOfString:@"/" options:NSBackwardsSearch];
    NSString *dir = [path substringToIndex:range.location];
    [self mkdirs:dir];
}

+ (BOOL)exists:(NSString *)path
{
    return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

+ (BOOL)deleteFile:(NSString *)path
{
    if (![FileUtil exists:path] || [path isEqualToString:@"/"]) {
        return NO;
    }
    return [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

+ (BOOL)deleteCacheDir:(NSString *)userId cacheType:(NSString *)cacheType
{
    NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    cacheDir = [NSString stringWithFormat:@"%@/%@/%@", cacheDir, userId, cacheType];
    return [FileUtil deleteFile:cacheDir];
}

+ (NSData *)saveImage:(UIImage *)image path:(NSString *)path
{
    [self mkdirsAtPath:path];
    NSData *imageData = [self compressImageQuality:image];
    [imageData writeToFile:path atomically:YES];
    return imageData;
}

+ (NSData *)compressImageQuality:(UIImage *)image
{
    CGFloat compression = 0.7;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    NSLog(@"source image size:%.2fkb", imageData.length / 1024.0);
    while (imageData.length > IMAGE_MAX_SIZE && compression > 0.1) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    NSLog(@"final image size:%.2fkb", imageData.length / 1024.0);
    return imageData;
}

+ (UIImage *)compressImageQualityToImage:(UIImage *)image
{
    if(image==nil){
        return image;
    }
    CGFloat compression = 0.7;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    NSLog(@"source image size:%.2fkb", imageData.length / 1024.0);
    while (imageData.length > IMAGE_MAX_SIZE && compression > 0.1) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    NSLog(@"final image size:%.2fkb", imageData.length / 1024.0);
    return [UIImage imageWithData:imageData];
}

+ (BOOL)copyFile:(NSString *)fromPath toPath:(NSString *)toPath
{
    BOOL bRet = NO;
    NSError *error;
    if ([FileUtil exists:fromPath]) {
        bRet = [[NSFileManager defaultManager] copyItemAtPath:fromPath toPath:toPath error:&error];
    }
    return bRet;
}

+ (void)clearCache:(NSString *)userId
{
    [FileUtil deleteCacheDir:userId cacheType:CACHE_TYPE_FILES];
    [FileUtil deleteCacheDir:userId cacheType:CACHE_TYPE_DOCS];
}

+ (UIImage *)imageWithPath:(NSString *)path
{
    NSString *fullPath = [self getFullPath:path];
    return [UIImage imageWithContentsOfFile:fullPath];
}

+ (NSInteger) getFileSize:(NSString*) path
{
    NSFileManager * filemanager = [[NSFileManager alloc]init];
    if([filemanager fileExistsAtPath:path]){
        NSDictionary * attributes = [filemanager attributesOfItemAtPath:path error:nil];
        NSNumber *theFileSize;
        if ( (theFileSize = [attributes objectForKey:NSFileSize]) )
            return  [theFileSize intValue]/1024;
        else
            return -1;
    }
    else
    {
        return -1;
    }
}

+ (BOOL)isFileDir:(NSString *)filePath
{
    BOOL isDir = NO;
    [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDir];
    return isDir;
}


@end
